<template>
  <div class="box">
    <div class="text">愿你遇见期待:123</div>
    <canvas ref='gua' width="200" height="100" id='gua'></canvas>
  </div>
</template>

<script >
import { getCurrentInstance, onMounted } from "vue";
export default {
  setup() {
    let {ctx}=getCurrentInstance()
    onMounted(() => {
      guas()
    });
    
    function guas() {
      let gua = ctx.$refs.gua
      gua.onselectstart=()=>false
      let ctxx = gua.getContext("2d");
      ctxx.save();
      ctxx.fillStyle = "gray";
      ctxx.fillRect(0, 0, gua.width, gua.height);
      ctxx.restore();
      console.log(111)
      gua.addEventListener("mousedown", function () {
        gua.addEventListener("mousemove", draw);
      });
      gua.addEventListener("mouseup", () => {
        gua.removeEventListener("mousemove", draw);
        if (flag > 200) {
          gua.style.opacity = 0;
          gua.addEventListener("transitionend", () => {
            gua.style.display = "none";
          });
        }
      })
      gua.addEventListener('mouseout',()=>{
           gua.removeEventListener("mousemove", draw);
      })

      let flag = 0;
      function draw(en) {
        let e = en || window.event;
        // let x = e.clientX - document.querySelector(".box").offsetLeft;
        // let y = e.clientY - document.querySelector(".box").offsetTop;
        let x=e.offsetX
        let y=e.offsetY
        ctxx.save();
        ctxx.lineJoin = "round";
        ctxx.lineCap = "round";
        ctxx.lineWidth = 10;
        ctxx.globalCompositeOperation = "destination-out";
        ctxx.beginPath();
        ctxx.moveTo(x, y);
        ctxx.lineTo(x + 1, y + 1);
        ctxx.stroke();
        ctxx.restore();
        flag++;
      }
    }
    return {}
  },
};
</script>

<style lang="less" scoped>
*{
    box-sizing: border-box;
}
.box {
  position: relative;
  width: 200px;
  height: 100px;
  border: 1px solid blue;
//   margin: 50px auto;
  text-align: center;
  overflow: hidden;
}
.text {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 100px;
  background-color: #000;
  color: #fff;
}
#gua {
  position: absolute;
  top: 0;
  left: 0;
  transition: 2s;
}
</style>